<template>
  <div class="app">
    <div class="loginall" :style="{ ...style }">
      <topColumn />
      <div class="login">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" :hide-required-asterisk="true" label-position="top">
          <div class="logintxt">
            <div>登录</div>
            <p></p>
          </div>
          <el-form-item prop="username" label="输入账号">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入您的账号" />
            <img v-show="isTick" class="tick" src="@/assets/images/tick.png" alt="" />
          </el-form-item>
          <el-form-item prop="password" label="输入密码">
            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="请输入您的密码" @keyup.enter.native="handleLogin" />
            <img v-show="isTicks" class="tick" src="@/assets/images/tick.png" alt="" />
          </el-form-item>
          <el-form-item v-if="captchaEnabled" prop="identify">
            <el-input v-model="loginForm.identify" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
          <!-- <div class="forgot">
              <router-link class="link-type" :to="'/register'">忘记密码</router-link>
            </div> -->
          <el-form-item style="width: 100%">
            <el-button :loading="loading" size="medium" type="primary" @click.native.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div v-if="register" style="float: right">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
        <!--  底部  -->
        <div class="el-login-footer">
          <span>技术支持：山东省水利勘测设计院有限公司</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { encrypt, decrypt } from './index.js'
import topColumn from '@/components/TopColumn/index.vue'
import { mapState } from 'vuex'
import { Message } from 'element-ui'
import { makeCode } from '@/utils'

export default {
  name: 'Login',
  components: { topColumn },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    const validateIdentify = (rule, value, callback) => {
      if (value.toLowerCase() !== this.identifyCode.toLowerCase()) {
        this.makeCode()
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }
    return {
      codeUrl: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '账号不能为空' }],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '密码不能为空',
            // validator: validatePassword,
          },
        ],
        identify: [{ required: true, trigger: 'blur', validator: validateIdentify }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: false,
      redirect: undefined,
      isTick: false,
      isTicks: false,
      stringval: '',
      style: {
        width: 1920 + 'px',
        height: 1080 + 'px',
        transform: 'scale(1) translate(-50%, -50%)',
      },
    }
  },
  computed: {
    ...mapState({
      token: (state) => state.user.token,
    }),
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true,
    },
    'loginForm.username': {
      handler(newv, oldv) {
        if (newv && newv != '') {
          this.isTick = true
        } else {
          this.isTick = false
        }
      },
      deep: true,
      immediate: true,
    },
    'loginForm.password': {
      handler(newv, oldv) {
        if (newv && newv !== '') {
          this.isTicks = true
        } else {
          this.isTicks = false
        }
      },
      deep: true,
      immediate: true,
    },
  },

  mounted() {
    this.setScale()
    setInterval(this.updateClock, 1000)

    this.makeCode()

    window.addEventListener('resize', () => this.Debounce(this.setScale, 0))
  },
  methods: {
    passwordinput(e) {
      if (this.loginForm.password !== '') {
        var password = this.hashPassword(e)
        this.stringval = password
      }
    },
    Debounce: (fn, t) => {
      console.log(123)
      const delay = t || 500
      let timer
      console.log(123)

      const args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      const context = this
      timer = setTimeout(() => {
        timer = null
        fn.apply(context, args)
      }, delay)
    },
    setScale() {
      // this.style.transform =
      //   "scale(" + this.getScale() + ") translate(-50%, -50%)";
      this.style.transform = 'scaleX(' + window.innerWidth / 1920 + ') scaleY(' + window.innerHeight / 1080 + ')  translate(-50%, -50%)'
      console.log(this.style)
    },

    getCurrentTime() {
      const currentDate = new Date()
      const hours = currentDate.getHours()
      const minutes = currentDate.getMinutes()
      const seconds = currentDate.getSeconds()
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    getCurrentDate() {
      const currentDate = new Date()
      const year = currentDate.getFullYear()
      const month = currentDate.getMonth() + 1
      const day = currentDate.getDate()
      const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      const dayOfWeek = daysOfWeek[currentDate.getDay()]
      return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${dayOfWeek}`
    },
    updateClock() {
      this.currentTime = this.getCurrentTime()
      this.currentDate = this.getCurrentDate()
    },
    makeCode() {
      this.identifyCode = makeCode(4)
      // console.log('identifyCode', this.identifyCode)
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && key >= 'a' && key <= 'z') || (!shiftKey && key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    hashPassword(passwored) {
      return encrypt(passwored)
    },

    handleLogin: function () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('permission/ResetPermissionsAndRoute')
          localStorage.setItem('username', JSON.stringify(this.loginForm.username))
          this.passwordinput(this.loginForm.password)
          const obj = {
            username: this.loginForm.username,
            password: this.stringval,
          }
          this.$store
            .dispatch('user/login', obj)
            .then((res) => {
              this.loading = false
              if (!this.$store.getters.token) {
                this.errorTime++
                this.makeCode()
                Message.error(res.data.msg)
                return
              }

              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery,
              })
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getRandomArbitrary(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.loginall {
  position: absolute;
  left: 50%;
  top: 50%;
  height: 100%;
  background-image: url('~@/assets/images/loginbg.png');
  background-size: 100% 100%;
  transform-origin: 0 0;
  overflow: hidden;
}

::v-deep(.el-form-item__label) {
  color: #afb8e3 !important;
}

::v-deep(.el-input--medium .el-input__inner) {
  // border-bottom: 3px solid #fff !important;
  // background-color: rgba(225, 225, 225, 0) !important;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  // background-image: url('~@/assets/img/login/login4/rvbg.png');
  background-size: 79% 57%;
  /* 可以调整背景图片的尺寸适应容器 */
  background-position: center center;
  /* 可以调整背景图片的位置 */
  background-repeat: no-repeat;
  /* 防止重复 */
  background-position: 57% 52%;
  height: calc(113% - 79px);
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  // border-radius: 6px;
  // background: #ffffff;
  // width: 400px;
  width: 600px;
  // padding: 25px 25px 5px 25px;
  padding: 85px 140px;
  background: linear-gradient(to bottom, rgba($color: #008d9b, $alpha: 0.7), rgba($color: #012d3a, $alpha: 0.7));
  border-radius: 15px;

  .logintxt {
    padding-bottom: 60px;

    div {
      font-size: 32px;
      line-height: 32px;
      color: #fff;
      font-weight: bold;
      padding-bottom: 8px;
    }

    p {
      margin: 0;
      width: 64px;
      height: 6px;
      background-color: #fff;
      border-radius: 10px;
    }
  }

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }

  .forgot {
    display: flex;
    justify-content: flex-end;
    padding: 20px 0 56px;

    a {
      color: #afb8e3;
    }
  }

  .el-form-item {
    margin-bottom: 0;
    margin-top: 55px;

    &:last-child {
      margin-bottom: 0;
      text-align: center;
    }

    .el-form-item__content {
      display: flex;
      align-items: center;
      position: relative;
      line-height: 48px;

      .el-input {
        input {
          border-radius: 0;
          border: 0;

          color: #fff;
          padding-left: 0;
        }
      }

      .tick {
        position: absolute;
        right: 0;
        top: 8px;
      }

      .el-button--medium {
        margin: 0 auto;
        width: 80%;
        font-size: 26px;
        background-color: #018a9a;
        border-radius: 30px;
        border: 0;
        padding: 13px 0;
      }
    }
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  // bottom: 0;
  bottom: 5vh;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  // font-size: 12px;
  font-size: 16px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
